package com.wjf.birdfish.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SecurityContextFilter implements Filter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private static final String FILTER_APPLIED = "SECURITY_CONTEXT_FILTER_APPLIED";
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if (request.getAttribute(FILTER_APPLIED) != null) {
			chain.doFilter(request, response);
			return;
		}
		request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
		HttpSession session = ((HttpServletRequest) request).getSession();
		SecurityContext context = (SecurityContext) session.getAttribute(SecurityContext.SECURITY_CONTEXT);
		if (context == null) {
			logger.debug("SecurityContext is null, create new SecurityContext.");
			context = SecurityContextHolder.createContext();
		} 
		if (!context.isLogined() && request.getParameter(SecurityContext.SECURITY_AREA) != null) {
			context.setArea(request.getParameter(SecurityContext.SECURITY_AREA));
		}
		logger.debug("Logic Area:" + context.getArea());
		SecurityContextHolder.setContext(context);
		chain.doFilter(request, response);
		try {
			session.setAttribute(SecurityContext.SECURITY_CONTEXT, context);
		} catch (Exception e) {}
		SecurityContextHolder.clearContext();
	}

	public void init(FilterConfig config) throws ServletException {}
	
	public void destroy() {}

}
